package com.qfedu.util;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

/**
 * @author lenovo
 * @version 1.0
 * @date 2023/4/4 17:55
 * @poject day04-myservlet
 */
public class DruidUtil {
    private static DataSource dataSource; //声明数据源

    //初始化连接池
    static {
        try {
            Properties properties = new Properties();//加载配置文件内容
            InputStream resourceAsStream = DruidUtil.class.getClassLoader().getResourceAsStream("druid.properties");
            properties.load(resourceAsStream); //加载配置文件
            ///通过静态工厂方法完成数据源初始化
            dataSource = DruidDataSourceFactory.createDataSource(properties); //得到的是DruidDataSource
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    //获取连接
    public static Connection getConnection(){
        Connection connection =null;
        try {
            connection = dataSource.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return connection;
    }
    //获取连接池
    public static  DataSource getDataSource(){
        return dataSource;
    }
}
